﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using QuTouTiaoAssist.Entity;
using QuTouTiaoAssist.Util;

namespace QuTouTiaoAssist
{
    public partial class FrmMyInfo : FrmBase
    {
        public FrmMyInfo()
        {
            InitializeComponent();
            ClearControls();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void ClearControls()
        {
            foreach (var control in this.Controls)
            {
                if (control.GetType() == typeof (TextBox))
                    (control as TextBox).Text = "";
            }
            UiUtil.ClearPictureBox(this.pbAvatar);
            this.linkLabelGift.Text = "无";
            this.linkLabelGift.Tag = null;
        }

        private void Info2Controls(QttMemberInfo info)
        {
            this.txtMemberId.Text = info.MemberId.ToString();
            this.txtMobile.Text = info.MobileNumber;
            this.txtNick.Text = info.NickName;
            this.txtBalance.Text = info.Balance;
            this.txtCoin.Text = info.Coin.ToString();
            this.txtInviteCode.Text = info.InviteCode;
            this.txtIsBindWX.Text = info.IsBindWeiXin == 1 ? "是" : "否";
            this.txtPupilNum.Text = info.PupilNumber.ToString();
            this.txtTeacherId.Text = info.TeacherId;
            this.txtIsFresher.Text = info.IsFresher ? "是" : "否";
            base.ChangeMainTitle(base.AppName + " - " + info.NickName);
            if (info.GiftNotice != null && info.GiftNotice.Id != null)
            {
                this.linkLabelGift.Text = info.GiftNotice.Desc;
                this.linkLabelGift.Tag = info.GiftNotice;
            }
            this.pbAvatar.BackgroundImage = QttHelper.GetImageByUrl(info.AvatarUrl);
            this.pbAvatar.BackgroundImageLayout = ImageLayout.Stretch;
        }

        void RefreshData()
        {
            if (!base.CheckLogin())
                return;

            ClearControls();
            new Thread(() =>
            {
                try
                {
                    if (!base.CheckLogin())
                        return;
                    var info = QttHelper.GetMemberInfo(base.MemeberToken);
                    base.InvokeCrossThread<QttMemberInfo>(Info2Controls, info.Data);
                }
                catch (Exception ex)
                {

                }
            }).Start();
        }

        private void btnOpenTreasure_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;

            new Thread(() =>
            {
                var treasureInfo = QttHelper.GetTreasureInfo(base.MemeberToken);
                if (treasureInfo.IsOpenTreasureAble)
                {
                    var result = QttHelper.OpenTreasureBox(base.MemeberToken);
                    if (result < 0)
                    {
                        MsgBox.ShowInfo("开宝箱失败，" + result);
                    }
                    else
                    {
                        MsgBox.ShowInfo("开宝箱成功，+" + result);
                    }
                }
                else
                {
                    MsgBox.ShowInfo("宝箱已开过，剩余时间为：" + treasureInfo.LeftTime);
                }
            }).Start();
            
        }

        private void btnShareToWx_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;

            new Thread(() =>
            {
                int result = QttHelper.ShareToWeiXin(base.MemeberToken);
                if (result < 0)
                {
                    MsgBox.ShowInfo("分享到朋友圈失败，" + QttHelper.GetErrorMessage(result));
                }
                else
                {
                    MsgBox.ShowInfo("分享到朋友圈成功，获取奖励：" + result);
                }
            }).Start();
        }

        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;

            new Thread(() =>
            {
                if (!QttHelper.IsTodaySignIn(base.MemeberToken))
                {
                    var result = QttHelper.SignIn(base.MemeberToken);
                    if (result.Code < 0)
                    {
                        MsgBox.ShowInfo("签到失败，" + result.Message);
                    }
                    else
                    {
                        MsgBox.ShowInfo(string.Format("签到成功，获取奖励：{0}，已连续签到：{1}天！",
                            result.Data.Amount,
                            result.Data.ContinuationSignIn));
                    }
                }
                else
                {
                    MsgBox.ShowInfo("今天已签到！");
                }
            }).Start();
        }

        private void btnModifyPwd_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;

            new FrmModifyPwd().ShowDialog();
        }

        private void btnModifyUserInfo_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;

            var result = new FrmModifyUserInfo(base.MemberInfo.NickName, base.MemberInfo.GetBirth()).ShowDialog();
            if (result == DialogResult.OK)
            {
                btnRefresh.PerformClick();
            }
        }

        private void linkLabelGift_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (this.linkLabelGift.Tag != null)
            {
                var info = this.linkLabelGift.Tag as QttGiftNotice;
                new Thread(() =>
                {
                    try
                    {
                        var result = QttHelper.ReceiveGift(base.MemeberToken, info.Id);
                        if (result.Code == 0)
                        {
                            MsgBox.ShowInfo("领取成功！");
                            this.btnRefresh.PerformClick();
                        }
                        else
                        {
                            MsgBox.ShowInfo("领取失败，" + result.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        MsgBox.ShowInfo("领取失败，" + ex.Message);
                    }
                }).Start();
            }
        }

        /// <summary>
        /// “绑定微信”按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBindWx_Click(object sender, EventArgs e)
        {
            if (!base.CheckLogin())
                return;
            
            new Thread(() =>
            {
                try
                {
                    var memberResult = QttHelper.GetMemberInfo(base.MemeberToken);
                    if (memberResult.Code == 0)
                    {
                        string wxOpenId = "o8qJqvwUlxHunE21J_ZUmVfebreg";
                        string avatarUrl = memberResult.Data.AvatarUrl;
                        string nickName = memberResult.Data.NickName;
                        var bindWxResult = QttHelper.BindWx(base.MemeberToken, wxOpenId, avatarUrl, nickName, 1);
                        if (bindWxResult.Code == 0)
                        {
                            var amount = bindWxResult.Data.Amount;
                            Console.WriteLine(amount);
                            MsgBox.ShowInfo("绑定成功！");
                        }
                        else
                        {
                            throw new Exception(bindWxResult.Message);
                        }
                    }
                    else
                    {
                        throw new Exception(memberResult.Message);
                    }
                }
                catch (Exception ex)
                {
                    MsgBox.ShowInfo("绑定失败，" + ex.Message);
                }
            }){IsBackground = true}.Start();
        }
    }
}
